home *** CD-ROM | disk | FTP | other *** search
- Path: noc.netcom.net!news
- From: Tarang Deshpande <tarang@willows.com>
- Newsgroups: comp.lang.c
- Subject: Re: Rounding a double
- Date: Tue, 02 Apr 1996 17:00:40 -0800
- Organization: NETCOM Network Operations
- Message-ID: <3161CDB8.6BB5@willows.com>
- References: <4jprh2$1li@newsgate.dircon.co.uk>
- NNTP-Posting-Host: daffy.willows.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0GoldB2 (Win95; I)
-
- Peter Smith wrote:
- >
- > Has anybody got a C function to round a double to a number of decimal
- > places that:
- > a) is readable
- > b) is relatively short
- > c) works !!
- > I had a function but it failed if the number of decimal places was zero,
- > if the double was very small, .. . etc etc.
- >
- > Is there a library of freeware C functions anywhere on the Internet ??
- >
- > Many thanks
- > Pete
- >
- > replies to : pg-smith@dircon.co.uk
-
- How about:
-
- #include <math.h>
- double rounddouble ( double number, int decimals )
- {
-
- long roundednumber;
-
- /* shift the decimal to the right by decimals places add 0.5 and truncate */
- roundednumber = ( long ) ( number * pow ( 10, decimals ) + 0.5 );
-
- /* shift the decimal to the left by decimals places */
- number = ( double )roundnumber / pow ( 10, decimals );
-
- return ( number );
- }
-
- Tarang
-